<template>
  <div style="width:100%" class="examination">
    <div>
      <van-form ref="examinationForm" :disabled="!mixEditable" label-position="top" class="demo-dynamic" size="mini">
          <van-field
            v-for="(topic, index) in topicList"
            :key="index"
            :prop="String(index)"
            :label-width="0"
            :rules="[{ required: topic.required && topic.type !== 'textarea', message: '此题不能为空' }]"
          >
            <template #input>
              <div class="question">
                {{ index+1 + '、' + topic.question }}
                <span v-if="topic.required == true"> (必填)</span>
              </div>
              <div v-if="topic.type === 'radio'">
                <div>
                  <van-radio-group v-model="valueObj[String(index)]" direction="horizontal">
                    <van-radio v-for="(option, optionIndex) in topic.options.split('&')" :key="optionIndex" :name="String(optionIndex + 1)" icon-size="14px">{{ option }}</van-radio>
                  </van-radio-group>
                </div>
              </div>
              <div v-else-if="topic.type === 'checkbox'">
                <van-checkbox-group v-model="valueObj[String(index)]" direction="horizontal">
                  <van-checkbox shape="square" v-for="(option, optionIndex) in topic.options.split('&')" :key="optionIndex" :name="String(optionIndex + 1)" icon-size="14px">{{ option }}</van-checkbox>
                </van-checkbox-group>
              </div>
              <div v-else-if="topic.type === 'textarea'" class="is_textarea">
                <van-field
                  v-model="valueObj[String(index)]"
                  rows="1"
                  autosize
                  type="textarea"
                  :rules="[{ required: topic.required, message: '此题不能为空' }]"
                />
              </div>
            </template>
          </van-field>
      </van-form>
    </div>
  </div>
</template>
<script>
import { isArray, debounce, cloneDeep } from 'lodash'
export default {
  name: 'examination',
  props: {
    // field
    value: '',
    mode: {
      default: "edit", // 编辑模式和 edit， 展示模式 view
    },
    DefaultTopicList: {
      type: Array,
      default: () => []
    },
    // 修改题目权限
    isManager: {
      type: Boolean,
      default: false
    },
    isResult: {
      type: Boolean,
      default: false
    }
  },
  computed: {
    isDesigner(){
      return this.$attrs._source === 'designer'
    },
    mixEditable() {
      return !(this.$attrs.readonly || this.$attrs.disabled) && this.mode === "edit"
    },
  },
  data() {
    return {
      separator: '&',
      topicList: [],
      radio: '',
      checkList: [],
      isWriting: !this.isManager,
      examList: [{
        type: 'radio',
        question: '单选',
        options: 'A&B&C&D',
        required: true
      }],
      valueObj: {},
      optionArr: []
    }
  },
  mounted(){
    this.optionArr = isArray(this.topicList) && this.topicList.map(v =>v.options && v.options.split(this.separator) || [''])
    // this.formatModel()
  },
  watch: {
    valueObj: {
      immediate: true,
      deep: true,
      handler(val) {
        let value = ''
        for(const v in val) {
          const temp = val[v] && isArray(val[v]) ? val[v].join(',') : val[v]
          value = v == 0 ? temp : value + '&' + temp
        }
        this.$emit('input', value)
      }
    },
    // isWriting: {
    //   immediate: true,
    //   handler(val) {
    //     if (val === true) {
    //       this.deb(this, this.topicList)
    //     }
    //   }
    // },
    optionArr: {
        immediate: true,
        deep: true,
        handler(val, oldval) {
          if (oldval !== undefined && this.topicList && isArray(this.topicList)) {
            this.topicList = this.topicList.map((item, index) => {
              if (item.type !== 'textarea') {
                item.options = val[index] && val[index].join(this.separator)
              }
              return item
            })
          }
        }
      },
    DefaultTopicList: {
      immediate: true,
      deep: true,
      handler(val, oldValue) {
        this.topicList = cloneDeep(val)
        this.formatModel()
      }
    }
  },
  methods: {
    // deb: debounce(
    //   (_that, val) => {
    //     console.log(val)
    //     _that.$emit('createSuccess', val)
    //   },
    //   300, // 延迟时间
    // ),
    formatModel() {
      let form = {}
      if (!this.value) {
        this.topicList && this.topicList.forEach((v, i) => form[String(i)]= v.type === 'checkbox' ? [] : '')
      } else {
        const valueArr = this.value && this.value.split('&')
        this.topicList && this.topicList.forEach((v, i) => {
          form[String(i)]= (v.type === 'checkbox' ? valueArr[i] && valueArr[i].split(',') || [] : valueArr[i] || '')
        })
      }
      this.$set(this, 'valueObj', cloneDeep(form))
    },

    // 题目相关方法
    addTopic(type) {
      console.log(type,'====type')
      this.topicList.push({
        type,
        question: '',
        options: '', //分隔符&
        required: false
      })
      this.optionArr = this.topicList.map(v =>v.options && v.options.split(this.separator) || [''])
      console.log(this.optionArr,'====optionArr')
    },
    addOptions(data) {
      console.log('addOptions',data)
      data.push('')
    },
    async switchtTopic() {
      this.isWriting = !this.isWriting
      if (this.isWriting) {
        this.$emit('createSuccess', this.topicList)
        // this.deb(this, this.topicList)
        this.formatModel()
        return this.topicList
      }
    },
    getAnswer() {
      let list = cloneDeep(this.topicList)
      for(const v in this.valueObj) {
        list[Number(v)].answer = isArray(this.valueObj[v])  ? this.valueObj[v].join('&') : this.valueObj[v]
      }
      // console.log(list,'===listy')
      return list
    }
  }
}
</script>
<style lang="scss" scoped>
// a_回答 q_问题
  .examination {
    float: left;
    .switch-btn {
      cursor: pointer;
      color: deepskyblue;
    }
    .a_options {
      padding-left: 22px;
    }
  }
  label.el-checkbox, label.el-radio {
    display: block;
  }
  label.el-radio {
    height: 28px;
  }
  .w-100 {
    width: 100%;
  }

.select-item {
  display: flex;
  flex-wrap: wrap;
  border: 1px dashed #fff;
  box-sizing: border-box;
  padding: 2px 0px;
  & .delete-btn {
    cursor: pointer;
    // color: #f56c6c;
    font-size: 20px;
    color: #b6b2b2;
    line-height: 35px;
    margin-left: 5px;
  }
  & .el-input + .el-input {
    margin-left: 4px;
  }
  &:hover {
    background: #efefef;
  }
  .select-line-icon {
    line-height: 32px;
    font-size: 16px;
    padding: 0 4px;
    color: #777;
  }
  .option-drag {
    cursor: move;
  }
  .q_options {
    display: flex;
    /* width: 75%; */
    margin-top: 9px;
    padding-right: 100px;
    min-width: 50%;
    max-width: 90%;
    .el-input {
      flex: 1;
    }
    .action {
      cursor: pointer;
      line-height: 30px;
      margin: 0 5px;
      font-size: 20px;
      color: #b6b2b2;
    }
  }
}
.ml-30 {
  margin-left: 30px;
}
.addTopic {
  width: 100%;
  margin-top: 5px;
}
.isresult {
  width: 100%;
  display: flex;
  div {
    flex: 1;
    margin-right: 10px;
  }
}
::v-deep .van-field__control.van-field__control--custom {
  text-align: left !important;
  display: block;
}
// .van-field__control--custom
.question {
  width: 100%;
}
.van-radio-group--horizontal, .van-checkbox-group--horizontal {
  display: block;
}
.van-radio.van-radio--horizontal, .van-checkbox.van-checkbox--horizontal {
    padding: 5px 0;
}
::v-deep .van-field--error .van-field__control, .van-field--error .van-field__control::placeholder {
  color: #333333
}

// 输入框偏左
::v-deep .van-cell .van-field__control {
  text-align: left !important;
}

.is_textarea .van-cell.van-field {
    padding: 0;
}
</style>